<?php
/**
 * 加密解密
 * @author justup@qq.com
 */
class T_code extends base{
	
	/**
	 * 加密
	 * @param mixed 	$value
	 * @param string	$key
	 * @param int		$expiry
	 * @return string
	 */
	public static function encode($value,$key = '',$expiry = 0){
		$time = time();
		$key 	= self::_getKey($key);
		$data 	= serialize(array('time'=>$time,'expiry'=>$expiry,'data'=>$value));
		$result = '';
		$keylen = strlen($key);
		$datalen = strlen($data);
		for($i = 0 ;$i <$datalen; $i++){
			$k = $i % $keylen;
			$result .= $data{$i} ^ $key{$k};
		}
		return base64_encode($result);
	}
	
	/**
	 * 解密
	 * @param string 	$code
	 * @param string	$key
	 * @return mixed
	 */
	public static function decode($code,$key = ''){
		$key 	= 	self::_getKey($key);
		$keylen = 	strlen($key);
		$str = '';
		$code = base64_decode($code);
		$datalen =	strlen($code);
		for($i = 0 ;$i <$datalen; $i++){
			$k = $i % $keylen;
			$str .= $code{$i} ^ $key{$k};
		}
		$data = unserialize($str);
		if($data===false){
			return false;
		}
		$time = time();
		if($data['expiry']==0 || $time-$data['time']<=$data['expiry']){
			return $data['data'];
		}else{
			return false;
		}
	}
	
	/**
	 * 获取key
	 */
	private static function _getKey($key){
		$key = md5($key ? $key :C('CODE/KEY'));
		return md5(substr($key,C('CODE/START'),C('CODE/END')).$key);
	}
}